<template>
  <div class="container">
    <!-- 使用搜索框组件 -->
    <SearchBox />
    <!-- 已保存城市列表 -->
    <div 
    class="add-city"
    v-for="(city, index) in savedCities"
    :key="index"
    @mouseenter="showButtons = index"
    @mouseleave="showButtons = -1"
  >
    <div class="a1">
      <div class="addleft">
        <h3>{{ city.name }}</h3>
        <span>{{ city.temp }}度</span>
      </div>
      <div class="button-city" v-show="showButtons === index">
        <button @click="$router.push({ name: 'CityView', params: { adcode: city.adcode } })">查看</button>
        <button @click="deleteCity(city.adcode)">删除</button>
      </div>
    </div>
  </div>

    <!-- 空状态提示 -->
    <div class="empty-message" v-show="!hasSavedCities">
      <p>暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</p>
    </div>
    <h2>近期天气</h2>
    <div class="forecast-section">
      

      <div class="forecast-cards">
        <div 
          class="forecast-card"
          v-for="(day, index) in forecastCards"
          :key="index"
        >
          <span class="day">{{ formatDay(index, day.week) }}</span>
          <span class="date">{{ formatDate(day.date) }}</span>
          <span class="weather-type">{{ day.dayweather }}</span>
          <span class="wind">风力 {{ day.daypower }}级</span>
        </div>
      </div>
      
      <div class="temperature-chart">
        <v-chart class="chart" :option="option" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed,  onBeforeUnmount } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent } from 'echarts/components'


import SearchBox from '@/components/SearchBox.vue'
import { getWeatherForecast } from '@/api/weatherApi'

use([CanvasRenderer, LineChart, GridComponent])

const showSearchResults = ref(false);

// 控制按钮显示
const showButtons = ref(false);
// 控制是否显示已保存城市列表
const hasSavedCities = ref(true); 



// const searchCity = ref('武汉')
const forecastData = ref(null)

// 图表配置
const option = ref({
  grid: {
    left: '5%',
    right: '5%',
    top: '5%',
    bottom: '5%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false,
  },
  yAxis: {
    type: 'value',
    show: false,
    min: function (value) {
      return Math.floor(value.min * 0.1)
    }
  },
  series: [
    {
      name: '白天',
      type: 'line',
      data: [],
      symbolSize: 8,
      symbol: 'circle',
      smooth: true,
      lineStyle: { width: 3, color: '#7EB3FF' },
      itemStyle: { color: '#7EB3FF', borderWidth: 2, borderColor: '#fff' },
      label: {
        show: true,
        position: 'top',
        formatter: '白{c}°C',
        color: '#FFFFFF',
        fontSize: 12,
        padding: [2, 4],
        distance: 6
      }
    },
    {
      name: '夜间',
      type: 'line',
      data: [],
      symbolSize: 8,
      symbol: 'circle',
      smooth: true,
      lineStyle: { width: 3, color: '#A7E25F' },
      itemStyle: { color: '#A7E25F', borderWidth: 2, borderColor: '#fff' },
      label: {
        show: true,
        position: 'bottom',
        formatter: '晚{c}°C',
        color: '#FFFFFF',
        fontSize: 12,
        padding: [2, 4],
        distance: 6
      }
    }
  ]
})

// 处理日期显示
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 处理星期显示
const formatDay = (index, week) => {
  const weekMap = ['日', '一', '二', '三', '四', '五', '六']
  // 前两日特殊处理
  if (index === 0) return '今天';
  if (index === 1) return '明天';
  
  return `周${weekMap[week % 7] || ''}`;
}

// 计算属性处理预报卡片数据
const forecastCards = computed(() => {
  return forecastData.value?.casts?.map((cast, index) => ({
    ...cast,
    // 添加week字段格式化（如果API返回的是数字）
    week: cast.week || `周${index + 1}` 
  })).slice(0, 4) || []
})

// 获取天气数据
const fetchWeatherData = async () => {
  try {
    const data = await getWeatherForecast('武汉') // 固定使用武汉
    forecastData.value = data
    
    // 更新图表数据
    option.value.xAxis.data = forecastCards.value.map((_, index) => formatDay(index))
    option.value.series[0].data = forecastCards.value.map(d => parseInt(d.daytemp))
    option.value.series[1].data = forecastCards.value.map(d => parseInt(d.nighttemp))
    option.value.xAxis.data = forecastCards.value.map((day, index) => 
      formatDay(index, day.week) // 添加week参数
    )
    
  } catch (error) {
    console.error('获取天气数据失败:', error)
    forecastData.value = null
  }
}

// 初始化加载数据
onMounted(fetchWeatherData)

// 已保存城市列表
const savedCities = ref([]);

// 安全获取localStorage数据
const loadSavedCities = () => {
  try {
    const savedData = localStorage.getItem('savedCities');
    if (savedData) {
      const parsed = JSON.parse(savedData);
      savedCities.value = Array.isArray(parsed) ? parsed : [];
    } else {
      savedCities.value = [];
    }
    // 根据是否有保存的城市设置空状态显示
    hasSavedCities.value = savedCities.value.length > 0;
  } catch (error) {
    console.error('加载保存的城市失败:', error);
    savedCities.value = [];
    hasSavedCities.value = false;
  }
};



// 删除城市
const deleteCity = (adcode) => {
  savedCities.value = savedCities.value.filter(c => c.adcode !== adcode);
  localStorage.setItem('savedCities', JSON.stringify(savedCities.value));
  hasSavedCities.value = savedCities.value.length > 0;
  
  // 触发事件通知Header组件更新按钮状态
  window.dispatchEvent(new Event('storage-update'));
};

// // 初始化时加载
onMounted(() => {
  loadSavedCities();
  document.addEventListener('click', handleClickOutside);
  window.addEventListener('storage-update', loadSavedCities);
});

// 组件卸载时清理
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
  window.removeEventListener('storage-update', loadSavedCities);
});

// 点击外部关闭搜索结果
const handleClickOutside = (event) => {
  const searchBox = document.querySelector('.search-box');
  if (searchBox && !searchBox.contains(event.target)) {
    showSearchResults.value = false;
  }
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  padding: 0 250px;
  margin: 0 auto;

  .empty-message {
    text-align: center;
    margin: 2rem  0 ;

    p {
      font-size: 1rem;
      color: rgba(255, 255, 255, 0.8);
    }
  }
  .add-city {
  display: flex;
  justify-content: space-between;
  width: 100%; // 确保宽度与input一致
  margin-top: 1rem;
  .a1{
    height: 44px;
    display: flex;
    justify-content: space-between;
    width: 100%;
  .addleft{
    display: flex;
    padding: 0.75rem 1rem;
    justify-content: space-between;
    width: 100%; // 占据整个宽度
    background-color: #004e71;
    transition:width 1s;
    h3 {
      margin: 0;
      font-size: inherit;
      font-weight: inherit;
    }
    &:hover {
    width: 90%;
    }
    
    
  }
  .button-city{
    display: flex;
    margin-bottom: 1rem;
    button{
      margin-left: 10px;
      height: 44px;
      text-align: center;
      opacity: 1;
      background-color: #eab308;
      width: 80px;
      cursor: pointer;
      font-family: inherit;
      font-size: 100%;
      font-weight: inherit;
      line-height: inherit;
      color: inherit;
      border: none;
    }

  }
}

}
  h2 {
      margin-bottom: 1rem;
      font-size: 1rem;
      font-weight: 250;
      margin-top: 24px;
    }


  .forecast-section {



    .forecast-cards {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0;
      background-color: #004e71;
      border-radius: 8px 8px 0 0;
      padding: 1.5rem 1.5rem 0 1.5rem;

      .forecast-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        padding: 1rem;
        gap: 1rem;
        text-align: center;
        height: 150px;
        width: 100px;
      }
    }

    .temperature-chart {
      position: relative;
      width: 100%;
      height: 300px;
      padding: 1.5rem;
      margin-bottom: 2rem;
      background-color: #004e71;
      padding: 1.5rem 1.5rem 0 1.5rem;

      .chart {
        position: absolute;
        left: 0;
        top: 0;
        width: 90%;
        height: 100%;
        user-select: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        padding: 1.5rem; 
        margin-left: 40px;
        border-width: 0;
      }
    }
  }
}
</style>